/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "user_command_handler.h"
#include "utils_log.h"
#include <chrono>
#include <iomanip>
#include <sstream>
#include <vector>
#include <algorithm> // 添加 algorithm 头文件用于 std::min
#include "common_version.h"
#include "common_product_definition.h"
#include "common_user_manager.h" // 添加 UserManager 头文件
#include "system_service.h" // 添加SystemService头文件

namespace El {
namespace Protocol {

void UserCommandHandler::RegisterMethodHandlers(
    std::unordered_map<std::string, std::function<nlohmann::json(const std::string &, const nlohmann::json &)>>
        &handlers)
{
    // 注册用户管理相关方法
    handlers["users.getList"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleUserGetList(id, params);
    };
    handlers["users.create"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleUserCreate(id, params);
    };
    handlers["users.update"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleUserUpdate(id, params);
    };
    handlers["users.delete"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleUserDelete(id, params);
    };
    handlers["users.changePassword"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleUserChangePassword(id, params);
    };
}

// 获取用户列表
nlohmann::json UserCommandHandler::HandleUserGetList(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理users.getList请求, 参数: {}", params.dump());

    auto &userManager = Common::UserManager::GetInstance();
    std::vector<Common::UserInfo> allUsers;
    if (!userManager.GetUserList(allUsers)) {
        EL_ERROR("获取用户列表失败");
        return CreateErrorResponse(id, 500, "获取用户列表失败");
    }

    // 处理分页参数
    int page = 1;
    int pageSize = 20; // 默认每页大小
    if (params.contains("page") && params["page"].is_number_integer()) {
        page = params["page"].get<int>();
        if (page < 1) page = 1; // 页码不能小于1
    }
    if (params.contains("page_size") && params["page_size"].is_number_integer()) {
        pageSize = params["page_size"].get<int>();
        if (pageSize < 1) pageSize = 1; // 每页大小不能小于1
    }

    // 处理角色过滤 (可选)
    std::vector<Common::UserInfo> filteredUsers;
    if (params.contains("role") && params["role"].is_string()) {
        std::string roleFilter = params["role"].get<std::string>();
        for (const auto &user : allUsers) {
            if (user.role == roleFilter) {
                filteredUsers.push_back(user);
            }
        }
    } else {
        filteredUsers = allUsers; // 没有过滤则使用全部用户
    }

    int totalUsers = filteredUsers.size();
    int startIndex = (page - 1) * pageSize;
    int endIndex = std::min(startIndex + pageSize, totalUsers);

    nlohmann::json userListJson = nlohmann::json::array();
    if (startIndex < totalUsers) {
        for (int i = startIndex; i < endIndex; ++i) {
            const auto &user = filteredUsers[i];
            nlohmann::json userJson;
            userJson["username"] = user.username;
            userJson["role"] = user.role;
            userJson["status"] = user.enabled ? "active" : "disabled";
            // 权限信息暂时省略，UserManager未提供
            // userJson["permissions"] = nlohmann::json::array();
            userListJson.push_back(userJson);
        }
    }

    // 构建符合协议规范的返回数据
    nlohmann::json resultData;
    resultData["total"] = totalUsers;
    resultData["page"] = page;
    resultData["page_size"] = pageSize;
    resultData["users"] = userListJson;

    return CreateSuccessResponse(id, resultData);
}

// 创建用户
nlohmann::json UserCommandHandler::HandleUserCreate(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理users.create请求, 参数: {}", params.dump());

    // 1. 校验参数
    if (!params.contains("username") || !params["username"].is_string() || params["username"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "用户名参数缺失或无效");
    }
    if (!params.contains("password") || !params["password"].is_string() || params["password"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "密码参数缺失或无效");
    }
    if (!params.contains("role") || !params["role"].is_string()) {
        return CreateErrorResponse(id, 400, "角色参数缺失或无效");
    }

    std::string username = params["username"].get<std::string>();
    std::string password = params["password"].get<std::string>();
    std::string role = params["role"].get<std::string>();

    // 2. 构造 UserInfo
    Common::UserInfo newUser;
    newUser.username = username;
    newUser.password = password; // UserManager内部会处理加密
    newUser.role = role;
    newUser.enabled = true; // 默认启用
    newUser.lastLoginTime = 0; // 初始登录时间为0

    // 3. 调用 UserManager 添加用户
    auto &userManager = Common::UserManager::GetInstance();
    if (!userManager.AddUser(newUser)) {
        // 检查是否是用户已存在导致的失败
        Common::UserInfo existingUser;
        if (userManager.GetUserInfo(username, existingUser)) {
            return CreateErrorResponse(id, 409, "用户名已存在");
        }
        EL_ERROR("添加用户 '{}' 失败", username);
        return CreateErrorResponse(id, 500, "创建用户失败");
    }

    EL_INFO("成功创建用户: {}", username);

    // 4. 构建成功响应
    nlohmann::json resultData;
    resultData["username"] = newUser.username;
    resultData["role"] = newUser.role;
    resultData["status"] = newUser.enabled ? "active" : "disabled";
    // 权限信息暂时省略
    // resultData["permissions"] = nlohmann::json::array();

    return CreateSuccessResponse(id, resultData);
}

// 更新用户
nlohmann::json UserCommandHandler::HandleUserUpdate(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理users.update请求, 参数: {}", params.dump());

    // 1. 校验参数
    if (!params.contains("username") || !params["username"].is_string() || params["username"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "username参数缺失或无效");
    }
    std::string username = params["username"].get<std::string>();

    // 2. 获取用户信息
    auto &userManager = Common::UserManager::GetInstance();
    Common::UserInfo userInfo;
    if (!userManager.GetUserInfo(username, userInfo)) {
        return CreateErrorResponse(id, 404, "用户不存在");
    }

    // 3. 更新用户信息 (根据传入参数)
    bool updated = false;
    if (params.contains("role") && params["role"].is_string()) {
        std::string newRole = params["role"].get<std::string>();
        // 校验角色是否有效
        if (newRole != "administrator" && newRole != "operator" && newRole != "viewer") {
            return CreateErrorResponse(id, 400, "无效的角色类型");
        }
        if (userInfo.role != newRole) {
            userInfo.role = newRole;
            updated = true;
        }
    }

    if (params.contains("status") && params["status"].is_string()) {
        std::string newStatus = params["status"].get<std::string>();
        bool newEnabled = (newStatus == "active");
        if (userInfo.enabled != newEnabled) {
            userInfo.enabled = newEnabled;
            updated = true;
        }
    }

    // 4. 如果有更新，则保存
    if (updated) {
        if (!userManager.UpdateUser(userInfo)) {
            EL_ERROR("更新用户 '{}' 失败", username);
            return CreateErrorResponse(id, 500, "更新用户失败");
        }
        EL_INFO("成功更新用户: {}", username);
    } else {
        EL_DEBUG("用户信息未发生变化，无需更新: {}", username);
    }

    // 5. 构建成功响应
    nlohmann::json resultData;
    resultData["username"] = userInfo.username;
    resultData["role"] = userInfo.role;
    resultData["status"] = userInfo.enabled ? "active" : "disabled";
    // 权限信息暂时省略
    // resultData["permissions"] = nlohmann::json::array();

    return CreateSuccessResponse(id, resultData);
}

// 删除用户
nlohmann::json UserCommandHandler::HandleUserDelete(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理users.delete请求, 参数: {}", params.dump());

    // 1. 校验参数
    if (!params.contains("username") || !params["username"].is_string() || params["username"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "username参数缺失或无效");
    }
    std::string username = params["username"].get<std::string>();

    // 2. 检查用户是否存在 (可选，但为了符合协议返回信息)
    auto &userManager = Common::UserManager::GetInstance();
    Common::UserInfo userInfo;
    if (!userManager.GetUserInfo(username, userInfo)) {
        // 用户不存在，根据协议可以认为删除成功（幂等性），或者返回404
        // 这里选择返回404，更明确
        return CreateErrorResponse(id, 404, "用户不存在");
    }

    // 3. 删除用户
    if (!userManager.DeleteUser(username)) {
        EL_ERROR("删除用户 '{}' 失败", username);
        // 理论上此时用户应该存在，若删除失败则认为是服务器内部错误
        return CreateErrorResponse(id, 500, "删除用户失败");
    }

    EL_INFO("成功删除用户: {}", username);

    // 4. 构建成功响应username
    nlohmann::json resultData;
    resultData["username"] = username;

    return CreateSuccessResponse(id, resultData);
}

// 修改密码
nlohmann::json UserCommandHandler::HandleUserChangePassword(const std::string &id, const nlohmann::json &params)
{
    EL_DEBUG("处理users.changePassword请求, 参数: {}", params.dump());

    // 1. 校验参数
    // 注意：根据当前UserManager::ChangePassword实现，username和old_password总是需要
    if (!params.contains("username") || !params["username"].is_string() || params["username"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "username参数缺失或无效");
    }
    if (!params.contains("old_password") || !params["old_password"].is_string() || params["old_password"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "old_password参数缺失或无效");
    }
    if (!params.contains("new_password") || !params["new_password"].is_string() || params["new_password"].get<std::string>().empty()) {
        return CreateErrorResponse(id, 400, "new_password参数缺失或无效");
    }

    std::string username = params["username"].get<std::string>();
    std::string oldPassword = params["old_password"].get<std::string>();
    std::string newPassword = params["new_password"].get<std::string>();

    // 2. 调用 UserManager 修改密码
    auto &userManager = Common::UserManager::GetInstance();
    if (!userManager.ChangePassword(username, oldPassword, newPassword)) {
        // ChangePassword 返回 false 可能因为用户不存在或旧密码错误
        // 无法精确区分，统一返回认证失败或用户不存在的错误
        Common::UserInfo tempUser;
        if (!userManager.GetUserInfo(username, tempUser)) {
             return CreateErrorResponse(id, 404, "用户不存在");
        }
        EL_WARN("用户 '{}' 修改密码失败 (可能是旧密码错误)", username);
        return CreateErrorResponse(id, 401, "旧密码错误或操作失败"); // 401 Unauthorized
    }

    EL_INFO("用户 '{}' 成功修改密码", username);

    // 3. 构建成功响应 (协议要求为空对象)
    nlohmann::json resultData = nlohmann::json::object();
    return CreateSuccessResponse(id, resultData);
}

} // namespace Protocol
} // namespace El